/* global window */
import pathToRegexp from 'path-to-regexp'
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { message } from 'antd'
import { UIStatus } from 'utils/enums'
import * as basicData from 'services/basicData.js'
import * as account from 'services/accout.js'
import * as entity from 'services/entity.js'
import * as customer from 'services/customer.js'
import * as service from 'services/servicefee.js'
import * as exchangeRate from 'services/exchangerate.js'
import * as companyAccount from 'services/adminCompanyAccount.js'
import { create, removeArrive, removePay, update, updateArrive, updatePay, query, queryAll, arrive, arrived, pay, paied, getNumber, querylist, addArriveThree } from 'services/transactionReceipt/transactionReceiptDetail.js'
import { pageModel } from '../common'

export default modelExtend(pageModel, {
  namespace: 'transactionReceiptDetail',
  state: {
    customerData: [],
    formType: '',
    toType: '',
    customerId: '',
    customerAccount: [],
    customerEntity: [],
    toClients: [],
    _toClients: [],
    fromClients: [],
    _fromClients: [],
    customerInfo: {},
    personId: '',
    companyAccount: [],
    currenciesTypeData: [],
    fundsTypeData: [],
    currenciesRateData: [],
    serviceAmountData: [],
    detailModalType: 'fromModal',
    entityVisible: false,
    accountVisible: false,
    showCustomerOperation: false,
    fromClientsKey: 0,
    toClientsKey: 0,
    fromCurrencyCode: '',
    toCurrencyCode: '',
    fromAmount: '',
    toAmount: '',
    amountLocal: 0,
    arrives: [],
    Pays: [],
    currentUIStatus: UIStatus.DEFAULT,
    transmodeCode: [],
    transactionNumber: '',
    transaction: [],
    transactionSelected: {},
    TransactionInfoVisible: false,
    data: {},
    matchType: 'edit'
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((pathname) => {
        const match = pathToRegexp('/transactionreceipt/detail/:id/:type').exec(pathname.pathname)
        const matchCustomerJump = pathToRegexp('/transactionreceipt/detail/new/:id/:type').exec(pathname.pathname)
        if (matchCustomerJump) {
          dispatch({
            type: 'initStore',
          })
          dispatch({
            type: 'getCustomer',
            payload: {
              customerNumber: matchCustomerJump[1],
            },
          })
          dispatch({ type: 'getNumber' })
          dispatch({ type: 'iniBasicData' })
        } else if (match) {
          dispatch({
            type: 'initStore',
          })
          dispatch({ type: 'query', payload: { id: match[1] } })
          dispatch({ type: 'updateEditState', payload: { showCustomerOperation: true, matchType: match[2] } })
          dispatch({ type: 'iniBasicData' })
        }
      })
    },
  },
  effects: {
    * getIdentifications ({ payload = {} }, { call, put }) {
      const response = yield call(customer.query, payload)
      const iden = response.data.identifications[0]
      if (response.code === 0) {
        yield put({
          type: 'updateCustomerInfo',
          payload: {
            number: iden && iden.number || '',
          },
        })
      }
    },
    * query ({ payload = {} }, { call, put }) {
      let sendData = {}
      sendData.id = payload.id
      const data = yield call(query, sendData)
      const { firstName, lastName, middleName, phoneNumber, customerNumber, fromClients, toClients, localRate } = data.data
      const { customerId, fromCurrencyCode, toCurrencyCode, fromAmount, toAmount, amountLocal, arrives, pays } = data.data
      if (data.success) {
        yield put({
          type: 'updateEditState',
          payload: {
            editType: 'update',
            data: data.data,
            customerInfo: {
              firstName,
              lastName,
              middleName,
              phoneNumber,
              customerNumber,
            },
            fromClients,
            toClients,
            _fromClients: fromClients,
            _toClients: toClients,
            customerId,
            fromClientsKey: fromClients.length,
            toClientsKey: toClients.length,
            fromCurrencyCode,
            toCurrencyCode,
            fromAmount,
            toAmount,
            amountLocal,
            arrives,
            pays,
            localRate,
            currentUIStatus: parseInt(data.data.status, 10),
            currentNZD: 'default',
          },
        })
        yield put({
          type: 'getCurrencyRate',
          payload: {
            currencyCodeFrom: fromCurrencyCode, // fromValue,
            currencyCodeTo: toCurrencyCode, // toValue,
          },
        })
        yield put({
          type: 'getCustomer',
          payload: {
            customerNumber,
          },
        })
      } else {
        message.error('get data failed')
        yield put({
          type: 'updateState',
          payload: {
            currentUIStatus: UIStatus.DEFAULT,
          },
        })
        throw data
      }
    },
    * getCustomer ({ payload = {} }, { call, put }) {
      const customerRes = yield call(customer.listall, { ...payload })
      if (customerRes.data.length > 0) {
        yield put ({
          type: 'getIdentifications',
          payload: {
            id: customerRes.data[0].id,
          },
        })
        yield put({
          type: 'updateState',
          payload: {
            customerInfo: customerRes.data[0],
            customerId: customerRes.data[0].id,
          },
        })
      }
    },
    * getNumber ({ payload }, { select, call, put }) {
      const transactionNumber = yield call(getNumber, payload)
      yield put({
        type: 'updateState',
        payload: {
          transactionNumber: transactionNumber.data,
        },
      })
    },
    * update ({ payload }, { select, call, put }) {
      const id = yield select(({ transactionReceiptDetail }) => transactionReceiptDetail.data.ID)
      const newReceipt = { ...payload, id }
      const data = yield call(update, newReceipt)
      if (data.success) {
        message.success('Update success')
        yield put({ type: 'query' })
      } else {
        message.success('Update failed')
        throw data
      }
    },

    * iniBasicData ({ payload = {} }, { call, put }) {
      yield put({ type: 'getCompanyAccount' })
      const currenciesData = yield call(basicData.listall, { type: 'Currencies' })
      const fundsTypeData = yield call(basicData.listall, { type: 'FundsType' })
      const serviceAmount = yield call(service.allbrif, { type: 'listAll' })
      const transmodeCode = yield call(basicData.listall, { type: 'TransmodeType' })
      if (currenciesData.success) {
        yield put({
          type: 'updateState',
          payload: {
            currenciesTypeData: currenciesData.data,
            fundsTypeData: fundsTypeData.data,
            serviceAmountData: serviceAmount.data,
            transmodeCode: transmodeCode.data,
          },
        })
      }
    },
    * getCustomerAccount ({ payload = {} }, { select, call, put }) {
      const { customerId } = yield select(_ => _.transactionReceiptDetail)
      payload.id = customerId
      const accountRes = yield call(account.list, { ...payload })
      let accountList = []
      accountRes.data.forEach(((value) => {
        accountList.push({ accountId: value.id, name: value.accountName })
      }))
      if (accountRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            customerAccount: accountList,
          },
        })
      }
    },

    * getCustomerEntity ({ payload = {} }, { select, call, put }) {
      const { customerId } = yield select(_ => _.transactionReceiptDetail)
      payload.id = customerId
      const entityRes = yield call(entity.list, { ...payload })
      let entityList = []
      entityRes.data.forEach(((value) => {
        entityList.push({ entityId: value.id, name: value.accountName })
      }))
      if (entityRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            customerEntity: entityList,
          },
        })
      }
    },
    * saveAll ({ payload }, { call, put }) {
      const match = pathToRegexp('/transactionreceipt/detail/:id/:type').exec(payload.pathname)
      const matchCustomerJump = pathToRegexp('/transactionreceipt/detail/new/:id').exec(payload.pathname)
      let response = {}
      let type = ''
      if (match) {
        response = yield call(update, payload.data)
        type = 'Update'
      } else if (matchCustomerJump) {
        response = yield call(create, payload.data)
        type = 'Create'
      }
      if (response.success) {
        message.success(`${type} success`)
      } else {
        message.error(`${type} failed`)
      }
    },
    * getCompanyAccount ({ payload = {} }, { call, put }) {
      const companyAccountRes = yield call(companyAccount.listall)
      let companyAccountList = []
      companyAccountRes.data.forEach(((value) => {
        companyAccountList.push({ companyAccountId: value.id, name: value.name })
      }))
      if (companyAccountRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            companyAccount: companyAccountList,
          },
        })
      }
    },
    * getCurrencyRate ({ payload }, { call, put }) {
      const currenciesData = yield call(exchangeRate.currency, { ...payload })
      if (currenciesData.success && currenciesData.data) {
        currenciesData.data.key = currenciesData.data.id
        // 一个对象转换为数组后放进数组里 [[]]
        let tempArr = []
        tempArr[0] = currenciesData.data
        yield put({
          type: 'updateState',
          payload: {
            currenciesRateData: tempArr,
          },
        })
      } else {
        message.warning('No current exchange rate was found')
        yield put({
          type: 'updateState',
          payload: {
            currenciesRateData: [],
          },
        })
      }
    },
    * showModal ({ payload }, { put }) {
      yield put({
        type: 'updateModalState',
        payload: { ...payload },
      })
    },
    * Arrives ({ payload }, { call, put, select }) {
      const { data, currentItem } = yield select(_ => _.transactionReceiptDetail)
      payload.arrive = { ...currentItem, ...payload.arrive }
      let response = {}
      if (payload.modalType === 'create') {
        response = yield call(arrive, payload)
      } else if (payload.modalType === 'update') {
        response = yield call(updateArrive, payload)
      }
      if (response.success) {
        message.success('Arrive success')
      } else {
        message.error('Arrive failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
        },
      })
    },
    * addArriveThree ({ payload }, { call, put }) {
      const data = yield call(addArriveThree, payload)
      if (data.success) {
        message.success('addArriveThree success')
      } else {
        message.error('addArriveThree falied')
      }
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          TransactionInfoVisible: false,
        },
      })
      yield put({
        type: 'query',
        payload: {
          id: payload.id1,
        },
      })
    },
    * Pays ({ payload }, { call, put, select }) {
      const { currentItem } = yield select(_ => _.transactionReceiptDetail)
      payload.pay = { ...currentItem, ...payload.pay, isThree: '' }
      let data = {}
      if (payload.modalType === 'create') {
        data = yield call(pay, payload)
      } else if (payload.modalType === 'update') {
        data = yield call(updatePay, payload)
      }
      if (data.success) {
        message.success('pays success')
      } else {
        message.error('pays failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
        },
      })
    },
    * delArrives ({ payload }, { call, put }) {
      let data = yield call(removeArrive, payload)
      if (data.success) {
        message.success('delete arrives success')
      } else {
        message.error('delete arrives failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
    },
    * delPays ({ payload }, { call, put }) {
      let data = yield call(removePay, payload)
      if (data.success) {
        message.success('delete pays success')
      } else {
        message.error('delete pays failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
    },
    * confirmArrives ({ payload }, { call, put }) {
      let data = yield call(arrived, payload)
      if (data.success) {
        message.success('confirm arrives success')
      } else {
        message.error('confirm arrives failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
    },
    * confirmPays ({ payload }, { call, put }) {
      let data = yield call(paied, payload)
      if (data.success) {
        message.success('confirm pays success')
      } else {
        message.error('confirm pays failed')
      }
      yield put({
        type: 'query',
        payload: {
          id: payload.id,
        },
      })
    },
    * getTransaction ({ payload }, { call, put }) {
      const data = yield call(querylist, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            transaction: data.data.data,
          },
        })
      }
    },
  },

  reducers: {
    initStore (state, { payload }) {
      payload = {
        customerData: [],
        formType: '',
        toType: '',
        customerId: '',
        customerAccount: [],
        customerEntity: [],
        toClients: [],
        _toClients: [],
        fromClients: [],
        _fromClients: [],
        customerInfo: {},
        personId: '',
        companyAccount: [],
        currenciesTypeData: [],
        fundsTypeData: [],
        currenciesRateData: [],
        serviceAmountData: [],
        detailModalType: 'fromModal',
        entityVisible: false,
        accountVisible: false,
        showCustomerOperation: false,
        fromClientsKey: 0,
        toClientsKey: 0,
        fromCurrencyCode: '',
        toCurrencyCode: '',
        fromAmount: '',
        toAmount: '',
        amountLocal: 0,
        arrives: [],
        Pays: [],
        currentUIStatus: UIStatus.DEFAULT,
        transmodeCode: [],
        transactionNumber: '',
        transaction: [],
        transactionSelected: {},
        TransactionInfoVisible: false,
        data: {},
        matchType: 'edit'
      }
      return { ...state, ...payload }
    },
    updateCustomerInfo (state, { payload }) {
      state.customerInfo = {...state.customerInfo, ...payload}
      return state
    },
    updateEditState (state, { payload }) {
      return { ...state, ...payload }
    },
    // 按下ok 修改数据并关闭dialog
    deletelocal (state, { payload }) {
      const { currentItem, arr, arrname } = payload
      state[arrname] = state[arrname].filter((item) => {
        if (typeof currentItem.id === 'undefined') {
          return item.index !== currentItem.index
        } else {
          return item.id !== currentItem.id
        }
      })
      state[`_${arrname}`] = state[`_${arrname}`].map((item) => {
        if (typeof currentItem.id === 'undefined') {
          return item.index !== currentItem.index
        } else {
          if (item.id === currentItem.id) {
            item = {...item,transactionId:null}
          }
          return item
        }
      })
      return {
        ...state,
      }
    },
    updateModal (state, { payload }) {
      const clientType = state.detailModalType === 'fromModal' ? 'fromClients' : 'toClients'
      if (state.modalType === 'update') {
        if (typeof state.currentItem.id === 'undefined') {
          state[clientType] = state[clientType].filter(item => item.index !== state.currentItem.index)
        } else {
          state[clientType] = state[clientType].filter(item => item.id !== state.currentItem.id)
        }
        state.currentItem = { ...state.currentItem, ...payload }
        state[clientType] = state[clientType].concat(state.currentItem)
      } else if (state.modalType === 'create') {
        payload = { ...payload, id: null }
        if (payload.type === '1') {
          payload = { ...payload, account: '', entity: '' }
        } else if (payload.type === '2') {
          payload = { ...payload, entity: '' }
        } else if (payload.type === '3') {
          payload = { ...payload, account: '' }
        }
        state[clientType] = state[clientType].concat(payload)
      }
      state[`_${clientType}`] = state[clientType]
      state[`${clientType}Key`] = state[`${clientType}Key`] + 1
      return {
        ...state,
        modalVisible: false,
      }
    },
  },
})
